import Taro, {Component, Config} from '@tarojs/taro'
import {View, Image, Swiper, SwiperItem, Text, Button} from '@tarojs/components'
import './index.less'
import {
  AtCurtain,
  AtIcon,
  AtActivityIndicator,
  AtMessage,
  AtTabs,
  AtTabsPane,
  AtCard,
  AtFab,
  AtFloatLayout,
  AtInputNumber,
  AtList,
  AtListItem,
  AtButton, AtBadge, AtModalHeader, AtModal, AtModalContent, AtModalAction, AtInput, AtTextarea,
} from "taro-ui";
import {inject, observer} from "@tarojs/mobx";
import QrCode from '../../assets/images/qrcode.jpg'

@inject('shoppingCarListStore')
@inject('locationStore')
@inject('userInfoStore')
@observer
export default class Home extends Component<any, any> {
  constructor(props) {
    super(props)
    this.state = {
      isOpened: false,
      classificationList: [],
      current: 0,
      foodDetailLoading: true,
      foodDetailList: {},
      shoppingCarOpened: false,
      shoppingCarIsEmpty: true,
      swiperList: [],
      totelPrice: 0,
      userNumber: '0',
      userNumberModel: true,
      orderListNoteModel: false,
      orderListNote: ''
    }
    //获取启动参数
    let {shop_id, location_id} = Taro.getLaunchOptionsSync().query
    //非公众号内进入
    if (!shop_id) {
      try {
        shop_id = Taro.getStorageSync('shop_id')
        location_id = Taro.getStorageSync('location_id')
      } catch (e) {

      }
      this.setState({
        userNumberModel: false
      })

      //公众号内进入
    } else {
      Taro.setStorage({
        key: "shop_id",
        data: shop_id
      })
      Taro.setStorage({
        key: "location_id",
        data: location_id
      })
    }

    this.props.locationStore.set({shopId: shop_id, locationId: location_id})
    Taro.setNavigationBarTitle({
      title: `食酷    桌号：${location_id || '无'}`
    })
    const openId = this.props.userInfoStore.get('openId')
    if (openId) {
      console.log('openId', openId);
    } else {
      Taro.login({
        success: ({code}) => {
          Taro.request({
            url: `${process.env.remoteUrl}/wx/code`,
            method: 'POST',
            header: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: {
              code: code
            }
          }).then(({data: res}) => {
            console.log('data', res.data);
            this.props.userInfoStore.set('openId', res.data)
            Taro.setStorage({
              key: 'openId',
              data: res.data
            })
          })
        }
      })
    }
  }

  showTabPage(index) {
    this.setState({
      foodDetailLoading: true,
      current: index
    })
    if (!this.state.foodDetailList[index]) {
      Taro.request({
        url: `${process.env.remoteUrl}/food?classificationId=${this.state.classificationList[index].id}`,
        method: 'GET'
      }).then(({data: res}) => {
        this.setState(prev => {
          prev.foodDetailList[index] = res.data
          return prev
        })
      }).finally(() => {
        this.setState({
          foodDetailLoading: false
        })
      })
    } else {
      this.setState({
        foodDetailLoading: false
      })
    }
  }

  componentWillMount() {
    Taro.request({
      url: `${process.env.remoteUrl}/classification?shopId=${this.props.locationStore.location.shopId}`,
      method: 'GET'
    }).then(({data: res}) => {
      this.setState({
        classificationList: res.data
      }, () => {
        this.showTabPage(0)
      })
    })
    Taro.request({
      url: `${process.env.remoteUrl}/swiper?shopId=${this.props.locationStore.location.shopId}`,
      method: 'GET'
    }).then(({data: res}) => {
      this.setState({
        swiperList: res.data
      })
    })

    Taro.request({
      url: `${process.env.remoteUrl}/shop?id=${this.props.locationStore.location.shopId}`,
      method: 'GET'
    }).then(({data: res}) => {
      this.props.locationStore.set({shop: res.data})
    })

  }


  config: Config = {
    navigationBarTitleText: '食酷'
  }


  render() {
    const tabList = this.state.classificationList.map(res => ({title: res.name}))
    const foodDetailList = this.state.foodDetailList
    return (
      <View className='index'>
        <AtMessage/>
        <AtModal closeOnClickOverlay={false} isOpened={this.props.locationStore.location.shopId == null}>
          <AtModalHeader>请在公众号内扫码点餐</AtModalHeader>
          <AtModalContent>
            <View className={'at-row at-row__justify--center'} style={{width: '100%', height: "100%"}}>
              <Image src={QrCode} style={{width: '160px', height: '160px'}}/>
            </View>
          </AtModalContent>
        </AtModal>
        <AtModal closeOnClickOverlay={false}
                 isOpened={this.props.locationStore.location.shopId && this.state.userNumberModel}>
          <AtModalHeader>请选择用餐人数</AtModalHeader>

          <AtModalContent>
            {
              [
                {value: '1'},
                {value: '2'},
                {value: '3'},
                {value: '4'},
                {value: '5'},
              ].map(v => {
                return (
                  <View key={v.value}
                        className={this.state.userNumber == v.value ? 'user-number-view user-number-choose-view'
                          : 'user-number-view'}
                        onClick={() => {
                          Taro.setStorage({
                            key: "user_number",
                            data: v.value
                          })
                          this.setState({
                            userNumber: v.value
                          })
                        }}>{v.value}
                  </View>
                )
              })

            }
            <View className={'user-number-view'} onClick={() => {
              this.setState({userNumber: 0})
            }}>
              <AtInput
                type='number'
                customStyle={{width: '50px'}}
                onChange={v => {
                  Taro.setStorage({
                    key: "user_number",
                    data: v
                  })
                  this.setState({
                    userNumber: v
                  })
                }}
                name={'userNumber'}/>
            </View>
          </AtModalContent>
          <AtModalAction>
            <Button
              type='primary'
              disabled={this.state.userNumber == '0'}
              onClick={() => {
                this.setState({
                  userNumberModel: false
                })
              }}>确定</Button>
          </AtModalAction>
        </AtModal>


        {/*<AtModal closeOnClickOverlay={false}*/}
        {/*         isOpened={this.state.orderListNoteModel}>*/}
        {/*  <AtModalHeader>备注</AtModalHeader>*/}
        {/*  <AtModalContent>*/}
        {/*    <View>*/}
        {/*      <AtTextarea*/}
        {/*        value={this.state.orderListNote}*/}
        {/*        onChange={v => {*/}
        {/*          this.setState({*/}
        {/*            orderListNote: v*/}
        {/*          })*/}
        {/*        }}*/}
        {/*        maxLength={20}*/}
        {/*      />*/}
        {/*    </View>*/}
        {/*  </AtModalContent>*/}
        {/*  <AtModalAction>*/}
        {/*    <Button*/}
        {/*      type='primary'*/}
        {/*      onClick={() => {*/}
        {/*        const shoppingCarList = [...this.props.shoppingCarListStore.shoppingCarList]*/}
        {/*        Taro.navigateTo({*/}
        {/*          url: `/pages/order/index?shoppingCarList=${JSON.stringify(shoppingCarList)}&note=${this.state.orderListNote}&peopleSum=${this.state.userNumber}`,*/}
        {/*          success: () => {*/}
        {/*            this.props.shoppingCarListStore.clear()*/}
        {/*            this.setState(prev => {*/}
        {/*              prev.shoppingCarOpened = false*/}
        {/*              prev.totelPrice = 0*/}
        {/*              prev.shoppingCarIsEmpty = true*/}
        {/*              prev.foodDetailList[this.state.current].forEach(v => {*/}
        {/*                v.number = 0*/}
        {/*              })*/}
        {/*              prev.orderListNoteModel = false*/}
        {/*            })*/}
        {/*          }*/}
        {/*        })*/}
        {/*      }}>确定</Button>*/}
        {/*  </AtModalAction>*/}
        {/*</AtModal>*/}


        <AtCurtain
          isOpened={this.state.isOpened}
          onClose={() => {
            this.setState({
              isOpened: false
            })
          }}>
          <Image
            style='width:100%;height:250px' src=''/>
        </AtCurtain>
        <View>
          <Swiper
            indicatorColor='#999'
            indicatorActiveColor='#333'
            circular
            indicatorDots
            autoplay>
            {
              this.state.swiperList.map(v => (
                <SwiperItem key={v.img}>
                  <Image style={{width: '100%'}} src={v.img}/>
                </SwiperItem>
              ))
            }
          </Swiper>
        </View>

        <AtTabs
          className={'at-tabs-cus'}
          ref={'atTabs'}
          current={this.state.current}
          tabList={tabList}

          height={Taro.getSystemInfoSync().windowHeight - 150 + 'px'}
          tabDirection='vertical'
          onClick={(value = 0) => {
            this.showTabPage(value)
          }}
          scroll>
          {
            this.state.classificationList.map((_, index) => (
              <AtTabsPane tabDirection='vertical'
                          current={this.state.current}
                          index={index}
                          key={index}
                          customStyle={{minHeight: '100%', width: '100%'}}>
                <AtActivityIndicator isOpened={this.state.foodDetailLoading}
                                     size={48} content='加载中...'
                                     color='green'
                                     mode='center'/>
                <View style={{
                  minHeight: "100%", textAlign: 'center',
                  fontSize: '18px', width: '100%',
                  padding: '10px 0'
                }}>
                  {
                    foodDetailList[index] && foodDetailList[index].map(k => (
                      <View style={{marginBottom: '10px', height: '100%'}} key={k.id}>
                        <AtCard title={k.name} customStyle={{textAlign: 'left'}}>
                          <View className='at-row'>
                            <Image
                              className={'at-col at-col-3'}
                              style='width: 60px;height:60px;background: #fff;'
                              src={k.img}
                            />
                            <View className='at-col at-col__offset-1 at-col-2' style={{textAlign: 'center'}}>
                              {k.price} 元
                            </View>
                            <View className='at-row at-col__offset-1'
                                  style={{marginTop: '24px', justifyContent: 'center'}}>
                              <AtInputNumber
                                min={0}
                                max={20}
                                step={1}
                                value={k.number || 0}
                                onChange={(number) => {
                                  if (number === 0) {
                                    this.props.shoppingCarListStore.remove(k)
                                  } else {
                                    this.props.shoppingCarListStore.add(k)
                                  }
                                  k.number = number
                                  let totelPrice = 0
                                  this.props.shoppingCarListStore.shoppingCarList.forEach(v => {
                                    totelPrice = totelPrice + v.price * v.number
                                  })
                                  this.setState({totelPrice})
                                }}
                                type='number'/>
                            </View>
                          </View>
                        </AtCard>
                      </View>
                    ))
                  }
                </View>
              </AtTabsPane>
            ))
          }
        </AtTabs>

        <View className='shopping-cart'>
          <AtFab onClick={() => {
            const {size} = this.props.shoppingCarListStore.shoppingCarList
            this.setState(prev => {
              prev.shoppingCarOpened = !prev.shoppingCarOpened
              prev.shoppingCarIsEmpty = size === 0
              return prev
            })
          }}>
            <AtBadge value={this.state.totelPrice + ' 元'}
                     customStyle={{width: '40px', fontSize: '40px', lineHeight: '40px'}}>
              <Text className='at-fab__icon at-icon at-icon-shopping-cart'/>
            </AtBadge>

          </AtFab>

        </View>
        <AtFloatLayout
          isOpened={this.state.shoppingCarOpened}
          title="菜篮子"
          customStyle={{minHeight: '900px'}}
          scrollWithAnimation
          onClose={() => {
            this.setState({
              shoppingCarOpened: false
            })
          }}>
          {
            this.state.shoppingCarIsEmpty ?
              <View className='at-row at-row__justify--center' style={{height: '100px', padding: '30px 0'}}>
                <AtIcon value='blocked' size='80' color='#DCDCDC'/>
              </View> : <View>
                <AtList>
                  {[...this.props.shoppingCarListStore.shoppingCarList].map(v => {
                    return <AtListItem
                      title={v.name}
                      extraText={'份数：' + v.number}
                      thumb={v.img}/>
                  })}

                  <View style={{margin: '10px 0'}}>
                    <AtTextarea
                      value={this.state.orderListNote}
                      placeholder={'备注'}
                      height={50}
                      onChange={v => {
                        this.setState({
                          orderListNote: v
                        })
                      }}
                      maxLength={20}
                    />
                  </View>
                  <AtButton customStyle={{marginTop: '15px'}} type='primary' size='normal'
                            onClick={() => {
                              const shoppingCarList = [...this.props.shoppingCarListStore.shoppingCarList]
                              Taro.navigateTo({
                                url: `/pages/order/index?shoppingCarList=${JSON.stringify(shoppingCarList)}&note=${this.state.orderListNote}&peopleSum=${this.state.userNumber}`,
                                success: () => {
                                  this.setState(prev => {
                                    prev.shoppingCarOpened = false
                                    prev.totelPrice = 0
                                    prev.shoppingCarIsEmpty = true
                                    prev.foodDetailList[this.state.current].forEach(v => {
                                      v.number = 0
                                    })
                                  })
                                  this.props.shoppingCarListStore.clear()
                                }
                              })
                            }}
                            circle>提交订单</AtButton>
                </AtList>
              </View>
          }
          <AtButton type='secondary' customStyle={{marginTop: '15px'}} circle onClick={() => {
            Taro.navigateTo({
              url: `/pages/order/index`,
            })
            this.setState({
              shoppingCarOpened: false
            })
          }}>查看订单</AtButton>
        </AtFloatLayout>
      </View>
    )
  }
}

